#pragma once

#include <vector>
#include <functional>
#include <ctime>
#include <iostream>
#include <unistd.h>
#include "log.hpp"

using task_t = std::function<void()>;
static const int gdefault_task_num = 5;


class TaskManager
{
public:
    TaskManager(int cap = gdefault_task_num):_cap(cap)
    {
        srand(time(nullptr));
        // _tasks.push_back([]()
        //                  { std::cout << "sub process[" << getpid() << " ] 执行访问数据库的任务\n"
        //                              << std::endl; });
        // _tasks.push_back([]()
        //                  { std::cout << "sub process[" << getpid() << " ] 执行url解析\n"
        //                              << std::endl; });
        // _tasks.push_back([]()
        //                  { std::cout << "sub process[" << getpid() << " ] 执行加密任务\n"
        //                              << std::endl; });
        // _tasks.push_back([]()
        //                  { std::cout << "sub process[" << getpid() << " ] 执行数据持久化任务\n"
        //                              << std::endl; });
       
    }
    bool PushTask(task_t&& task)
    {
        if(_tasks.size() == _cap)
            return false;
        _tasks.push_back(std::move(task));
        return true;
    }
    //随机选择任务编号
    int SelectTask()
    {
        return rand() % _tasks.size();
    }
    void Excute(int number)
    {
        if(number > _tasks.size() || number <0)
            return;
        _tasks[number]();
    }
private:
    std::vector<task_t> _tasks;
    int _cap;
};

TaskManager tm;

//主工作逻辑
void Worker()
{
    while(1)
    {
        int cmd = 0;
        //从标准输入读取（重定向）
        int n = ::read(0,&cmd,sizeof(cmd));
        if(n == sizeof(cmd))
        {
            tm.Excute(cmd);
        }
        else if(n == 0)
        {
            //写端关闭，进程退出
            LogModule::LOG(LogModule::INFO) <<"pid:"<<::getpid()<<" quit";
            break;
        }
        else
        {
            LogModule::LOG(LogModule::ERROR)<<"read erro";
        }
    }
}